#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Author：xiang
# @Date  ：2025/5/21 9:06
import pymysql
import logging

class Conn:

    def __init__(self):
        self.configs = {
            'test': {
                'host': '121.196.229.181',
                'port': 3306,
                'user': 'root',
                'password': '20240510',
                'database': 'ry_cloud_prod'
            },
            'pressure': {
                'host': '192.168.10.95',
                'port': 30850,
                'user': 'root',
                'password': '20240510',
                'database': 'ry_cloud'
            }
        }
        self.logger = logging.getLogger(__name__)

    def get_connection(self, env):
        """获取数据库连接"""
        if env not in self.configs:
            raise ValueError(f"未知的环境配置: {env}，可用环境: {list(self.configs.keys())}")

        config = self.configs[env]
        try:
            return pymysql.connect(
                host=config['host'],
                port=config['port'],
                user=config['user'],
                password=config['password'],
                database=config['database'],
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor  # 返回字典格式的结果
            )
        except Exception as e:
            self.logger.error(f"连接数据库失败: {str(e)}")
            raise

    def execute_update(self, env, sql):
        conn = None
        try:
            conn = self.get_connection(env)
            with conn.cursor() as cursor:
                affected_rows = cursor.execute(sql)
            conn.commit()
            return affected_rows
        except Exception as e:
            self.logger.error(f"执行更新操作失败: {str(e)}\nSQL: {sql}")
            if conn:
                conn.rollback()
            return 0
        finally:
            if conn:
                conn.close()

    def execute_query(self, env, sql):
        conn = None
        try:
            conn = self.get_connection(env)
            with conn.cursor() as cursor:
                cursor.execute(sql)
                return cursor.fetchall()
        except Exception as e:
            self.logger.error(f"执行查询操作失败: {str(e)}\nSQL: {sql}")
            return []
        finally:
            if conn:
                conn.close()

    def execute_query_one(self, env, sql):
        conn = None
        try:
            conn = self.get_connection(env)
            with conn.cursor() as cursor:
                cursor.execute(sql)
                return cursor.fetchone()
        except Exception as e:
            self.logger.error(f"执行查询单条操作失败: {str(e)}\nSQL: {sql}")
            return None
        finally:
            if conn:
                conn.close()
